/*
 * author bianlongting
 * date   2016-03-16
 * time   15:50
 * description 活动管理
 */

$(function(){
	var select_coupon = $(".select_coupon");
	var check = $(".check");
	var search = $(".btn-search");
	var page = $("#page");
	var pageIndex = 1;	//页码默认为第一页
	var pageCount;		//总页码
	var couponid;
	select_coupon.on("mouseover",function(){
		var that = $(this);
		var children = that.children('ul');
		var oLis = children.find("li");
		children.show();
		oLis.eq(0).addClass("actived")
				  				 .siblings().removeClass("actived");
		oLis.on("mouseover",function(){
			$(this).addClass("actived")
				   .siblings().removeClass("actived");
		});
	}).on("mouseout",function(){
		var that = $(this);
		var children = that.children('ul');
		children.hide();
	});

	check.on("click",function(){
		var parents = $(this).parents(".select_coupon");
		var data = {};
		couponid = parents.data().couponid;
		data.couponId = couponid;
		queryUsage(data);
	});

	//查询订单
	search.on("click",function(){
		var that = $(this);
		var data = {};
		data.couponId = couponid;
		data.sn = that.parents("form").find(".ticket").val();
		data.orderId = that.parents("form").find(".coupon").val();
		queryUsage(data);
	});
	
	//页码切换
	function changePage(num){
		page.find('a').on("click",function(e){
			e.preventDefault();
			var that = $(this);
			var data = {};
			var parent = that.parent();
			if (parent.hasClass("next")) {
				if (pageIndex == num) {
					return false;
				}else{
					pageIndex ++ ;
				}
			}else if (parent.hasClass("prev")) {
				if (pageIndex == 1) {
					return false;
				}else{
					pageIndex -- ;
				}
			}else {
				pageIndex = parseInt(that.text());
			};
			data.couponId = couponid;
			data.page = pageIndex;
			queryUsage(data);
		})
	};

	//查询订单使用情况
	function queryUsage(data){
		$.ajax({
			url : "/index.php?m=Home&c=Activity%2FManageActivity&a=getusecouponinfo",
			data : data,
			type : 'POST',
			dataType : 'JSON',
			success : function(data){
				if (data.success == true && data.data != "") {
					var html = "";
					$(".popmask,.use-situation").show();
					var info = data.data.info;
					var len = info.length;
					for (var i = 0; i < len; i++) {
						html += "<tr align='center'>\
									<td>" + info[i].sn + "</td>\
									<td>" + info[i].bindingtime + "</td>\
									<td>" + info[i].orderid + "</td>\
								</tr>"
					};
					$(".already-used").html(html);
					var count = parseInt(data.data.count);
					pageCount = Math.ceil(count/5);
					if (pageCount > 1) {
						page.html(data.data.show);
					}else{
						page.html("");
					}
					changePage(pageCount);		//切换页码
				}else{
					$(".toast_tip").html(data.message);
			        $(".toast").fadeIn('1000');
			        setTimeout(function(){
			            $(".toast").fadeOut();
			        },1000);
			        return false;
				}
			}
		})
	}

	//点击遮罩层隐藏遮罩和优惠券使用
	$(".popmask").on("click",function(){
		$(this).hide();
		$(".use-situation").hide();
	})

})